import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userinfo: {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo
  },
}

const actions = {
  // 登陆的操作，将token存储到state和cookie
  async login({ commit }, userInfo) {
    const { account, password } = userInfo
    const data = await login({ account: account.trim(), password: password })
    commit('SET_TOKEN', 'Bearer ' + data.token)
    setToken(data.token)
  },

  // 获取用户资料
  async getInfo({ commit }) {
    const data = await getInfo()
    commit('SET_USERINFO', data.userinfo)
    return data
  },

  logout({ commit }) {
    removeToken()
    resetRouter()
    commit('RESET_STATE')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
